package helper

import (
	"crypto/tls"
	"crypto/x509"
	"google.golang.org/grpc/credentials"
	"io/ioutil"
)

func GetServeCreds() (credentials.TransportCredentials, error) {
	// TLS认证
	//从证书相关文件中读取和解析信息，得到证书公钥、密钥对
	cert, err := tls.LoadX509KeyPair("keys/server.pem", "keys/server.key")
	if err != nil {
		return nil, err
	}
	certPool := x509.NewCertPool() //初始化一个CertPool
	ca, err := ioutil.ReadFile("keys/ca.pem")
	if err != nil {
		return nil, err
	}
	certPool.AppendCertsFromPEM(ca)          //解析传入的证书，解析成功会将其加到池子中
	creds := credentials.NewTLS(&tls.Config{ //构建基于TLS的TransportCredentials选项
		Certificates: []tls.Certificate{cert},        //服务端证书链，可以有多个
		ClientAuth:   tls.RequireAndVerifyClientCert, //要求必须验证客户端证书
		ClientCAs:    certPool,                       //设置根证书的集合，校验方式使用 ClientAuth 中设定的模式
	})
	return creds, nil
}

func GetClientCreds() (credentials.TransportCredentials, error) {
	// TLS连接
	//从证书相关文件中读取和解析信息，得到证书公钥、密钥对
	cert, err := tls.LoadX509KeyPair("keys/client.pem", "keys/client.key")
	if err != nil {
		return nil, err
	}
	certPool := x509.NewCertPool()
	ca, err := ioutil.ReadFile("keys/ca.pem")
	if err != nil {
		return nil, err
	}
	certPool.AppendCertsFromPEM(ca)

	creds := credentials.NewTLS(&tls.Config{
		Certificates: []tls.Certificate{cert}, //客户端证书
		ServerName:   "www.p-pp.cn",           //注意这里的参数为配置文件中所允许的ServerName，也就是其中配置的DNS...
		RootCAs:      certPool,
	})
	return creds, nil
}
